﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Altairis.Web.UI {
    public static class KeyedUrl {

        public static string CreateKey(string s) {
            if (string.IsNullOrEmpty(s)) return string.Empty;
            s = s.RemoveDiacritics().ToLower();
            s = Regex.Replace(s, "[^a-z0-9]", "-");
            s = s.Trim('-');
            while (s.IndexOf("--") > -1) s = s.Replace("--", "-");
            return s;
        }

        public static int ExtractItemIdFromUrl() {
            HttpContext context = HttpContext.Current;
            if (context == null) throw new InvalidOperationException("No current HTTP context available.");
            return ExtractItemIdFromUrl(context.Request.PhysicalPath);
        }

        public static int ExtractItemIdFromUrl(string fileName) {
            if (fileName == null) throw new ArgumentNullException("fileName");
            if (string.IsNullOrEmpty(fileName)) throw new ArgumentException("Value cannot be null or empty string.", "fileName");

            string key = System.IO.Path.GetFileNameWithoutExtension(fileName);

            if (Regex.IsMatch(key, "^[0-9]{1,}$")) {
                return int.Parse(key);
            }
            else if (!Regex.IsMatch(key, "^[0-9]{1,}-")) {
                return 0;
            }
            else {
                return int.Parse(key.Split('-')[0]);
            }
        }

    }

}
